#!/usr/bin/env python
# coding: utf-8

import re
import os
import sys
import time
import json

# path=os.getcwd()
# if path not in sys.path:
#     sys.path.append(path)

from onshs.tnxxxcfg_basecase import *



class HwMon(TnxxxCfg_BaseCase) :
    """
    HwMon
    """
    OPTIONS = [
        {
           'opt' : '--ip',
           'dest': 'ip',
           'metavar' : 'IP',
           'help' : 'the ip of ne',
           'required' : False,
           'default' : "10.15.1.32"
        },
        # {
        #     'opt' : '--cfgfile',
        #     'dest': 'cfgfile',
        #     'metavar' : 'PATH',
        #     'help' : 'the file of ip list configuration',
        #     'required' : False,
        #     'default' : "ip765.txt"
        # },
    ]

    def get_iplist(self):
        iplist_filted = []
        if os.path.isfile(os.getcwd()+r'/'+ self.iplistfile):
            iplist = open(os.getcwd()+r'/'+ self.iplistfile)
        else:
            return iplist_filted

        for line in iplist:
            if re.match(r'^\s*$', line) is not None : continue # 忽略空白行
            if re.match(r'^\s*#', line) is not None : continue # 忽略注释行
            iplist_filted.append(line.strip('\n'))

        iplist.close()

        return iplist_filted

    def check_alm(self,target_fid,target_almid):
        master_opct_slot = 0
        cmd_str = "$.dbgcli.0.Cmd \"connect\""
        rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), master_opct_slot, MTN_PORT)
        sessionId_str = rtn_str.split('"',2)[1].split('=')[1].strip(' ')
        # print(sessionId_str)
        # cmd_str = "$.dbgcli.0.Cmd \"list almcurrent\""
        # rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, MTN_PORT)
        # print(rtn_str)
        cmd_str = "$.dbgcli.0.Cmd \"queryasyn valid %s, almcurrent, (xflag,Fid,Almid,Level,Starttime,Endtime,Almsn,Slot), *\"" % (sessionId_str)
        rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), master_opct_slot, MTN_PORT)
        # print(rtn_str)
        # num = rtn_str.count(" - ")
        # context = rtn_str.split(" - ", num)[num]
        # print(context)
        fid_str = rtn_str.split("Fid", 1)[1].split("Almid", 1)[0].split("\r\n")[1].strip(' ')
        almid_str = rtn_str.split("Almid", 1)[1].split("Level", 1)[0].split("\r\n")[1].strip(' ')
        # print("Fid:%s" % (fid_str))
        # print("Almid:%s" % (almid_str))
        fid_list = fid_str.split(',')
        almid_list = almid_str.split(',')
        # print(fid_list,almid_list)

        for fid,alm in zip(fid_list,almid_list):
            if target_fid == fid.strip('"') and str(target_almid) == alm:
                print("Fid:%s occur alm %s" % (fid,alm))
                return True

        return False

    def check_cardfailure(self):
        cnt = 1
        slot = 10
        fid = "\\s=%s\\c=1" % (slot)

        while cnt:
            cnt -= 1
            # check card online status
            offline = self.check_alm(fid, 104)
            if offline:
                time.sleep(60 * 3)
                continue
            # check cardfailure status
            cardfailure = self.check_alm(fid, 106)
            # if alarm, get debug info
            if cardfailure:
                cmd_str = r'(unsigned short)(*(0xa0000000+0x6*2))'
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                scratch =  int(re.findall("value = (\d+) =", rtn_str, re.I)[0])
                print ("cardfailure, scratch:0x%x" % (scratch))
                # return
            # if normal, do some laser operate, then restart card
            # else:
                # cmd_str = r'ColdReboot'
                # rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                # print("reboot card")
            time.sleep(5)
            cmd_str = r'ColdReboot'
            rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
            print("reboot card")

    def hwmon(self):
        slot = 10
        cnt = 10
        checkword = [0x55, 0xaa, 0x7e, 0x81]

        while cnt:
            cnt -= 1

            for val in checkword:
                cmd_str = r'*(unsigned short*)(0xa0000000+0x6*2) = (unsigned short)'+str(val)
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                cmd_str = r'(unsigned short)(*(0xa0000000+0x6*2))'
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                scratch =  int(re.findall("value = (\d+) =", rtn_str, re.I)[0])
                result = (scratch&0xff)
                if  result == val:
                    print ("Result:0x%x, check success" % (result))
                else:
                    print ("Result:0x%x, check fail" % (result))
                    return
            time.sleep(1)


    def testcpld(self):
            slot = 10
            cnt = 100

            while cnt:
                cnt -= 1
                cmd_str = r'*(unsigned short*)(0xa0000000+0x6*2) = (unsigned short)'+str(0xc5)
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                cmd_str = r'*(unsigned short*)(0xa0000000+0x11*2) = (unsigned short)'+str(0xff)
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)

                # cmd_str = r'dbg_CpldMphgf01Init'
                # rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)

                cmd_str = r'*(unsigned short*)(0xa0000000+0x6*2) = (unsigned short)'+str(0x00)
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                cmd_str = r'*(unsigned short*)(0xa0000000+0x10*2) = (unsigned short)'+str(0x00)
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                cmd_str = r'*(unsigned short*)(0xa0000000+0x11*2) = (unsigned short)'+str(0x00)
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                cmd_str = r'(unsigned short)(*(0xa0000000+0x45*2))'
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                cfpctrl =  int(re.findall("value = (\d+) =", rtn_str, re.I)[0])
                cmd_str = r'*(unsigned short*)(0xa0000000+0x45*2) = (unsigned short)'+str(cfpctrl | 0x2)
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                cmd_str = r'*(unsigned short*)(0xa0000000+0x6*2) = (unsigned short)'+str(0x55)
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)

                cmd_str = r'(unsigned short)(*(0xa0000000+0x6*2))'
                rtn_str = self.tnxxx.send_rtn_str(cmd_str, self.get_ne_ip(0), slot, DEV_PORT)
                scratch =  int(re.findall("value = (\d+) =", rtn_str, re.I)[0])
                print( "testcpld cnt:%d, result:0x%x" % (cnt,scratch))
                time.sleep(1)

    def _execute(self):
        # self.iplistfile = self.options.cfgfile
        # ip_list = self.get_iplist()
        ip_list = self.options.ip.split(',')
        for ip in ip_list:
            self.set_ne_ip(0, ip)
            # self.tnxxx.disconnect()                    
            # self.hwmon()
            # self.check_cardfailure()
            self.testcpld()
            
        return True

if __name__ == "__main__" :
    case = HwMon()
    case.execute()
